package cytj.setup.fragment;

import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import cytj.setup.R;
import cytj.setup.activity.SetupActivity;
import cytj.setup.base.MyAPP;
import cytj.setup.util.CharacterTool;

/**
 * 节点部署的Fragment隶属于SetupActivity
 * Created by LTP on 2015/12/21
 */
public class NodesDeployFragment extends Fragment implements View.OnClickListener {
    /**
     * NodesDeployFragment的视图
     */
    private View view;
    /**
     * 节点ID/显示节点ID/节点位置/运行基站载波频率/发送时长/部署基站ID/显示部署基站ID/运行基站ID 的编辑框
     */
    private EditText editText_nodesID, editText_showNodesID, editText_nodesPosition, editText_frequency, editText_sendTime, editText_deployBaseID, editText_showDeployBaseID, editText_operationBaseID;
    /**
     * 节点类型的编辑框
     */
    private Spinner spinner_nodesType;
    /**
     * 节点部署的按键
     */
    private Button button_deployNodes;
    /**
     * 调试用TAG
     */
    private static final String TAG = "LTP";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_nodes_deploy, container, false);
        initView();
        return view;
    }

    /**
     * 控件初始化
     */
    private void initView() {
        editText_deployBaseID = (EditText) view.findViewById(R.id.editText_deployBaseID_nodesDeployFragment);
        editText_showDeployBaseID = (EditText) view.findViewById(R.id.editText_showDeployBaseID_nodesDeployFragment);
        editText_nodesPosition = (EditText) view.findViewById(R.id.editText_nodesPosition_nodesDeployFragment);
        editText_nodesPosition.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                // 节点位置用2个字节表示，禁止用户输入大于65535的数
                if (!s.toString().equals("") && Integer.parseInt(s.toString()) > 65535) {
                    Toast.makeText(getActivity(), "请输入小于65535的数！", Toast.LENGTH_SHORT).show();
                    editText_nodesPosition.setText(s.subSequence(0, s.length() - 1));
                    editText_nodesPosition.setSelection(s.length() - 1);
                }
            }
        });
        editText_nodesID = (EditText) view.findViewById(R.id.editText_nodesID_nodesDeployFragment);
        editText_showNodesID = (EditText) view.findViewById(R.id.editText_showNodesID_nodesDeployFragment);
        spinner_nodesType = (Spinner) view.findViewById(R.id.spinner_nodesType_nodesDeployFragment);
        editText_operationBaseID = (EditText) view.findViewById(R.id.editText_operationBaseID_nodesDeployFragment);
        editText_frequency = (EditText) view.findViewById(R.id.editText_frequency_nodesDeployFragment);
        editText_sendTime = (EditText) view.findViewById(R.id.editText_sendTime_nodesDeployFagment);
        editText_sendTime.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                // 发送时长用1个字节表示，禁止用户输入大于255的数
                if (!s.toString().equals("") && Integer.parseInt(s.toString()) > 255) {
                    Toast.makeText(getActivity(), "请输入小于255的数！", Toast.LENGTH_SHORT).show();
                    editText_sendTime.setText(s.subSequence(0, s.length() - 1));
                    editText_sendTime.setSelection(s.length() - 1);
                }
            }
        });
        button_deployNodes = (Button) view.findViewById(R.id.button_deployNodes_nodesDeployFragment);
        button_deployNodes.setOnClickListener(this);
        view.findViewById(R.id.relativeLayout_nodesDeployFragment).setOnClickListener(this);
    }

    /**
     * 根据节点类型获取节点类型码
     *
     * @param nodesType 0x01-检测静态停车，0x02-交通详情， 0x04-交通汇总，0x08-模拟地感线圈
     */

    private String getNodesType(String nodesType) {
        String treatyCode = "01";
        switch (nodesType) {
            case "检测静态停车":
                treatyCode = "01";
                break;
            case "交通详情":
                treatyCode = "02";
                break;
            case "交通汇总":
                treatyCode = "04";
                break;
            case "模拟地感线圈":
                treatyCode = "08";
                break;
        }
        return treatyCode;
    }

    public void setEditText_showDeployBaseID(String showDeployBaseID) {
        editText_showDeployBaseID.setText(showDeployBaseID);
    }

    public void setEditText_showNodesID(String nodesID) {
        editText_showNodesID.setText(nodesID);
    }

    public void setButton_deployNodes() {
        button_deployNodes.setText("部署");
        button_deployNodes.setBackgroundResource(R.drawable.shape_button);
        button_deployNodes.setClickable(true);
    }


    @Override
    public void onClick(View v) {
        String deployBaseID = editText_deployBaseID.getText().toString();
        String nodesID = editText_nodesID.getText().toString();
        String nodesType = getNodesType(spinner_nodesType.getSelectedItem().toString());
        String operationBaseID = editText_operationBaseID.getText().toString();
        String frequency = editText_frequency.getText().toString();
        String sendTime = editText_sendTime.getText().toString();
        String nodesPosition = editText_nodesPosition.getText().toString();
        switch (v.getId()) {
            case R.id.button_deployNodes_nodesDeployFragment:
                // 点击节点部署的按键
                editText_showNodesID.setText("");
                if (!MyAPP.getMyAPPInstance().isBluetoothConnected()) {
                    Toast.makeText(getActivity(), "请先连接蓝牙！", Toast.LENGTH_SHORT).show();
                } else if (deployBaseID.length() != 6 || nodesID.length() != 6 || operationBaseID.length() != 4 || TextUtils.isEmpty(nodesPosition) || TextUtils.isEmpty(frequency) || TextUtils.isEmpty(sendTime)) {
                    Toast.makeText(getActivity(), "请将信息填写完整", Toast.LENGTH_SHORT).show();
                } else {
                    String protocol = "ABAB" + deployBaseID + "F010" + nodesID + nodesType + operationBaseID;
                    frequency = CharacterTool.intToHexString(frequency, 3);
                    sendTime = CharacterTool.intToHexString(sendTime, 1);
                    nodesPosition = CharacterTool.intToHexString(nodesPosition, 2);
                    protocol += frequency + sendTime + nodesPosition + "00000000";
                    String xor = CharacterTool.xor(CharacterTool.hexStringToBytes(protocol), CharacterTool.hexStringToBytes(protocol).length);
                    protocol = protocol.substring(0, 14) + xor + protocol.substring(14);
                    Log.d(TAG, "发送部署请求的协议：" + CharacterTool.splitData(protocol));
                    ((SetupActivity) getActivity()).bluetoothService.write(CharacterTool.hexStringToBytes(protocol));
                    button_deployNodes.setClickable(false);
                    button_deployNodes.setBackgroundResource(R.drawable.shape_button_pressed);
                    nodesDeployCountDownTimer.start();
                }
                break;
            case R.id.relativeLayout_nodesDeployFragment:
                //点击EditText外部隐藏键盘
                InputMethodManager imm = (InputMethodManager)
                        getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                break;
        }
    }

    /**
     * 部署按键按下后倒计时120秒
     */
    public CountDownTimer nodesDeployCountDownTimer = new CountDownTimer(121000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            button_deployNodes.setText("正在部署，请稍候... " + millisUntilFinished / 1000);
        }

        @Override
        public void onFinish() {
            Toast.makeText(getActivity(), "超时,部署失败", Toast.LENGTH_SHORT).show();
            button_deployNodes.setText("部署");
            button_deployNodes.setBackgroundResource(R.drawable.shape_button);
            button_deployNodes.setClickable(true);
        }
    };
}
